package com.gdt.bdMessageQueue.advisory;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.advisory.AdvisorySupport;
import org.apache.activemq.command.ActiveMQDestination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 代理监听Queue的Queue负责监听服务端新开启queue的监听会触发事件，服务端Queue的监听关闭也会触发事件
 * @author zst
 *
 */
@Component
public class Advisory {
	@Autowired
	ConsumerAdvisoryListener consumerAdvisoryListener;
	
    protected static String brokerURL = "tcp://localhost:61616";
    protected static transient ConnectionFactory factory;
    protected transient Connection connection;
    protected transient Session session;
    
    public Advisory() throws Exception {
    	factory = new ActiveMQConnectionFactory(brokerURL);
    	connection = factory.createConnection();
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    }
    
    public void startAdvisory(String topic) throws Exception{
    	Advisory advisory = new Advisory();
		Session session = advisory.getSession();
    	ActiveMQDestination destination = (ActiveMQDestination)session.createQueue(topic);
		
		Destination consumerTopic = AdvisorySupport.getConsumerAdvisoryTopic(destination);
		System.out.println("Subscribing to advisory " + consumerTopic);
		MessageConsumer consumerAdvisory = session.createConsumer(consumerTopic);
		consumerAdvisory.setMessageListener(consumerAdvisoryListener);
		
    }
    

	public Session getSession() {
		return session;
	}
}
